//
//  RegisterViewController.m
//  iWeddingDirectory
//
//  Created by Tung Ngo on 6/6/12.
//  Copyright (c) 2012 Home. All rights reserved.
//

#import "RegisterViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "API.h"

@implementation RegisterViewController
@synthesize textFieldName;
@synthesize textFieldEmail;
@synthesize textFieldPassword;
@synthesize textFieldWebsite;
@synthesize textViewMessage;
@synthesize textFieldMobile;
@synthesize waitingIndicator;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"Register";
    
    textViewMessage.layer.borderWidth = 1.0f;
    textViewMessage.layer.borderColor = [UIColor blackColor].CGColor;
}

- (void)viewDidUnload
{
    [self setTextFieldName:nil];
    [self setTextFieldEmail:nil];
    [self setTextFieldWebsite:nil];
    [self setTextViewMessage:nil];
    [self setTextFieldMobile:nil];
    [self setWaitingIndicator:nil];
    [self setTextFieldPassword:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc {
    [textFieldName release];
    [textFieldEmail release];
    [textFieldWebsite release];
    [textViewMessage release];
    [textFieldMobile release];
    [waitingIndicator release];
    [textFieldPassword release];
    [super dealloc];
}

#pragma mark - Text field delegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (textField == textFieldMobile) {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.25];
        [self.view setTransform:CGAffineTransformMakeTranslation(0, -120)];
        [UIView commitAnimations];
    }
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    if (textField == textFieldMobile) {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.25];
        [self.view setTransform:CGAffineTransformMakeTranslation(0, 0)];
        [UIView commitAnimations];
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - Text view delegate

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.25];
    [self.view setTransform:CGAffineTransformMakeTranslation(0, -120)];
    [UIView commitAnimations];
    return YES;
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.25];
    [self.view setTransform:CGAffineTransformMakeTranslation(0, 0)];
    [UIView commitAnimations];
    return YES;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    
    return YES;
}

#pragma mark - Notification Handlers

- (void)onRegister:(NSNotification *)notification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kRegisterNotification object:nil];
    
    [waitingIndicator stopAnimating];
    [self.view setUserInteractionEnabled:YES];
    
    NSString *status = [notification.userInfo objectForKey:@"status"];
    if (status == nil || [status isEqualToString:@"error"]) {
        NSString *message = [notification.userInfo objectForKey:@""];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        [alert release];
        return;
    }
    else if ([status isEqualToString:@"ok"]) {
        NSString *password = [notification.userInfo objectForKey:@"user_pass"];
        NSNumber *userId = [notification.userInfo objectForKey:@"ID"];
        
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:userId forKey:@"userId"];
        [defaults setObject:password forKey:@"password"];
        [defaults synchronize];
    }
}

#pragma mark - Button Clicked Handlers

- (IBAction)buttonSubmit:(id)sender {
    NSString *username = textFieldName.text;
    NSString *email = textFieldEmail.text;
    NSString *password = textFieldPassword.text;
    NSString *website = textFieldWebsite.text;
    NSString *message = textViewMessage.text;
    NSString *mobile = textFieldMobile.text;
    
    NSString *msg = nil;
    if (username == nil || username.length == 0) {
        msg = @"Username is required";
    }
    else if (email == nil || email.length == 0) {
        msg = @"Email is required";
    }
    else if (password == nil || password.length == 0) {
        msg = @"Password is required";
    }
    else if (website == nil || website.length == 0) {
        msg = @"Website is required";
    }
    else if (message == nil || message.length == 0) {
        msg = @"Message is required";
    }
    else if (mobile == nil || mobile.length == 0) {
        msg = @"Mobile is required";
    }
    if (msg != nil) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        [alert release];
        return;
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onRegister:) name:kRegisterNotification object:nil];
    
    [waitingIndicator setHidesWhenStopped:YES];
    [waitingIndicator setHidden:NO];
    [waitingIndicator startAnimating];
    [self.view setUserInteractionEnabled:NO];
    
    API *api = [API sharedInstance];
    [api registerWithUsername:username email:email password:password website:website message:message mobile:mobile];
}

@end
